/*
  File: BaseInterceptor.cs
  Author: rcrxy
  CreateTime: 2025/07/02 15:52

  Description:
*/

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using StudentVideo.Data.Entities;
using StudentVideo.Extensions;

namespace StudentVideo.Interceptors;

public class BaseInterceptor(IHttpContextAccessor httpContextAccessor): SaveChangesInterceptor {
   private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor;

   public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result) {
      var context = eventData.Context;

      if (context == null)
         return base.SavingChanges(eventData, result);

      var entries = context.ChangeTracker
           .Entries()
           .Where(e => e.Entity is BaseEntity && (e.State == EntityState.Modified || e.State == EntityState.Added));

      foreach (var entry in entries) {
         var entity = (BaseEntity)entry.Entity;

         // 如果是新增实体，设置 CreateAt 和 UpdateAt
         if (entry.State == EntityState.Added) {
            entity.CreateAt = DateTime.Now;
            entity.UpdateAt = DateTime.Now;
         }

         // 如果是更新实体，设置 UpdateAt
         if (entry.State == EntityState.Modified) {
            entity.UpdateAt = DateTime.Now;
         }

         if (_httpContextAccessor is null)
            continue;

         if (_httpContextAccessor.HttpContext is null)
            continue;

         var userData = _httpContextAccessor.HttpContext.GetUserData();

         if (userData is null)
            continue;

         // 如果是新增实体，设置 CreateBy 和 UpdateBy
         if (entry.State == EntityState.Added) {
            entity.CreateBy = userData.UserId;
            entity.UpdateBy = userData.UserId;
         }

         // 如果是更新实体，设置 UpdateBy
         if (entry.State == EntityState.Modified) {
            entity.UpdateBy = userData.UserId;
         }
      }

      return base.SavingChanges(eventData, result);
   }
}
